<!--
选择器组件
@author:何世华
@2.0.0 支持选项内label
@1.0.1 修复二次选择的bug
@1.0.0 优化自动选择
-->
<template>
  <div :id="id" class="picker" :style="is_show?'right:0':'right:-100%'" @tap.self="close">
    <div class="picker_body" @tap.stop="">
      <div>
        {{msg}}
      </div>
      <div class="picker_title">
        <div @click="close" class="picker_btn_cancel">
          取消
        </div>
        <div class="picker_text">
          {{title}}
        </div>
        <div @click="close" class="picker_btn_ok">
          确定
        </div>
      </div>
      <div class="picker_item_title" v-if="item_title">
        <div class="picker_item_title_item" v-for="(list,index) in data"
             :style="{'flex':width_ratio&&width_ratio[index]?width_ratio[index]:1,'-webkit-flex':width_ratio&&width_ratio[index]?width_ratio[index]:1}"
        >
          {{item_title[index]}}
        </div>
      </div>
      <div class="picker_main" @touchstart="">
        <template v-for="(list,index) in data">
          <div class="picker_list" :data-index="index"
               style="transform:translate3d(0px, 0px, 0px) scale(1);-webkit-transform:translate3d(0px, 0px, 0px) scale(1);"
               :style="{'flex':width_ratio&&width_ratio[index]?width_ratio[index]:1,'-webkit-flex':width_ratio&&width_ratio[index]?width_ratio[index]:1}"
               @touchstart="scrollStart"
               @touchmove="scrolling"
               @touchend="scrollEnd">
            <div class="picker_item"></div>
            <div class="picker_item"></div>
            <div class="picker_item"
                 :data-index="sub_index"
                 :class="{'selected':cur_val[index]==item}"
                 :style="cur_val[index]==item?selected_style:''"
                 v-for="(item,sub_index) in list">
              {{item}}
            </div>
            <div class="picker_item"></div>
            <div class="picker_item"></div>
          </div>
          <div class="picker_label" v-if="cLabel[index]">
            <div class="picker_label_inner">
              {{cLabel[index]}}
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<style>
  .picker {
    position: fixed;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 10000;
    /*display:none;*/
  }

  .picker_btn_cancel {
    color: #999999;
    font-size: 0.7rem;
  }

  .picker_btn_ok {
    color: #d1a86a;
    font-size: 0.7rem;
  }

  .picker_item_title {
    display: flex;
    display: -webkit-flex;
  }

  .picker_item_title .picker_item_title_item {
    flex: 1;
    -webkit-flex: 1;
    padding: 0.5rem 0;
    text-align: center;
    font-size: 0.7rem;
  }

  .picker_body {
    position: absolute;
    bottom: 0;
    width: 100%;
    background: #fff;
    z-index: 10001;
  }

  .picker_title {
    display: flex;
    display: -webkit-flex;
    text-align: center;
    border-bottom: 1px solid #ebebeb;
  }

  .picker_title > * {
    line-height: 2.975rem;
    flex: 1;
    -webkit-flex: 1;
  }

  .picker_title > .picker_text {
    flex: 3;
    -webkit-flex: 3;
  }

  .picker_main {
    display: flex;
    display: -webkit-flex;
    overflow: hidden;
    height: 13.5rem;
    position: relative;
  }

  .picker_list {
    flex: 1;
    -webkit-flex: 1;
    text-align: center;
    /*transition: transform 0.1s;*/
    /*overflow: hidden;*/
    /*height: 100000%;*/
  }

  .picker_label {
    display: flex;
    display: -webkit-flex;
  }

  .picker_label_inner {
    /*position: absolute;*/
    top: 0;
    bottom: 0;
    height: 2.7rem;
    line-height: 2.7rem;
    text-align: center;
    margin: auto 0.5rem;
  }

  .picker_main:before {
    content: '';
    position: absolute;
    top: 5.4rem;
    width: 100%;
    background: rgba(239, 239, 239, 1);
    height: 2.7rem;
    z-index: -1;
  }

  .picker_item {
    height: 2.7rem;
    line-height: 2.7rem;
    z-index: 10001;
    color: #666666;
  }

  .picker_item.selected {
    color: #eabf50;
  }
</style>
<script>
  import $ from 'n-zepto';

  export default {
    name: 'sh-picker',
    props: [
      'id',//唯一标识
      'value',//v-model绑定value
      'data',//列表数据，二维数组
      'title',//标题
      'item_title',//选项标题
      'is_show',//是否展示
      'selected_style',//选中样式
      'width_ratio',//宽度比
      'label',//内标签
    ],
    data() {
      return {
//                currentValue:this.value,
        curData: null,
        cur_val: [],
        token: '',
        hadInited: false,
        scroll_data: {
          picker_item_height: 0,
          cur_translate_val: 0,
          scrolling_event: null,
          touch_start_pageY: 0,
        },
        isScrolling: false,
        msg: '',
        cLabel: [],
      }
    },
    beforeMount: function () {
      //初始化选项
      for (var i = 0; i < this.data.length; i++) {
        this.cur_val.push(this.data[i][0]);
      }
    },
    mounted: function () {
      this.cLabel = this.label || [];
    },
    updated: function () {
      var _self = this;
      if (_self.is_show && !_self.hadInited) {
        _self.init();
      }
    },
    methods: {
      init() {
//                console.log('初始化数据');
        this.scroll_data.picker_item_height
          = parseFloat($('#' + this.id + ' ' + ".picker_item").css('height').replace('px', ''));
//                console.log($('#'+_self.id+' '+".picker_item").css('height'));

        //自动选择
//                console.log(_self.value);
        if (this.value && this.data.length > 0) {
//                    _self.cur_val = _self.value;
//                console.log($('#'+_self.id+' '+'.picker_list'));
          for (var i = 0; i < this.value.length; i++) {
            for (var j = 0; j < this.data[i].length; j++) {
              if (this.value[i] == this.data[i][j]) {
//                                console.log(i,j);
//                                _self.scrollToItem(i,j);
                this.scrollToItem(i, j, true);
              }
            }
          }
        }
        this.hadInited = true;
      },
      //点击item
      clickItem(e) {
        var $parent = $(e.target).parents('.picker_list');
        var $this = $(e.target);
        var cur_list_index = $parent[0].dataset.index;
        var cur_item_index = $this[0].dataset.index;
//                console.log('点击item',cur_list_index,cur_item_index);
        this.scrollToItem(cur_list_index, cur_item_index);
      },
      //滚动
      scrollStart(e) {
//                this.msg='滚动开始';
        e.preventDefault();
        var _self = this;
        /*if($(e.target).html()==''){
            return;
        }*/
        var $this = $(e.target).parents('.picker_list');
        _self.scroll_data.scrolling_event = e;
        _self.scroll_data.touch_start_pageY = e.touches[0].pageY;
        //当前tansform的Y轴值
        var cur_translate_val = _self.getTranformY($this);
        _self.scroll_data.cur_translate_val = cur_translate_val;

//        console.log(_self.scroll_data.scrolling_event);
//        console.log(_self.scroll_data.cur_translate_val);
      },
      scrolling(e) {
        var _self = this;

//        console.log(_self.scroll_data.scrolling_event);
        if (!_self.scroll_data.scrolling_event) {
          return;
        }
        var $this = $(_self.scroll_data.scrolling_event.target).parents('.picker_list');
        if (_self.scroll_data.scrolling_event) {
          //处理触碰距离过短
          var touch_distance = e.touches[0].pageY - _self.scroll_data.touch_start_pageY;
          touch_distance = touch_distance < 0 ? -touch_distance : touch_distance;

//          console.log(e.touches[0].pageY);
//          console.log(_self.scroll_data.touch_start_pageY);
          if (touch_distance < 3) {
            return;
          } else {
            _self.isScrolling = true;
          }
//                    console.log('滚动中');
//                    console.log('滚动中',_self.scrolling_event,$this);
//                    console.log('鼠标位置:',
//                        _self.scrolling_event.touches[0].pageY,
//                        e.touches[0].pageY);
          var distance = _self.scroll_data.cur_translate_val + e.touches[0].pageY - _self.scroll_data.touch_start_pageY;
//          console.log('滑动距离', distance);
          $this.css({
            /*'transition': 'transform 0s',
            'webkitTransition': 'transform 0s',
            'webkitTransform':'translateY('+distance+'px)',
            'transform':'translateY('+distance+'px)'*/

            /*'transition': 'margin-top 0s',
            'webkitTransition': 'margin-top 0s',
            'margin-top':distance+'px'*/

            'transition': 'transform 0s',
            '-webkit-transition': '-webkit-transform 0s',
            'transition-property': '-webkit-transform',
            'transform-origin': '0px 0px 0px',
            'transform': 'translate3d(0px, ' + distance + 'px, 0px) scale(1)',
            '-webkit-transform': 'translate3d(0px, ' + distance + 'px, 0px) scale(1)',
          });
        }
      },
      scrollEnd(e) {
//                this.msg='';
        var _self = this;
        if (!_self.scroll_data.scrolling_event) {
          return;
        }
        var pre_event = _self.scroll_data.scrolling_event;
        var cur_event = e;
        var $this = $(pre_event.target).parents('.picker_list');
//                console.log('滚动结束',$this);
        if (_self.isScrolling) {
          _self.isScrolling = false;
        } else {
//                    console.log('滚动结束',$this[0].dataset.index,$(pre_event.target)[0].dataset.index);
          if ($(e.target).html() == '') {
            return;
          }
          _self.scrollToItem($this[0].dataset.index, $(pre_event.target)[0].dataset.index);
          return;
        }


        var time_distance = cur_event.timeStamp - pre_event.timeStamp;
//                console.log('滚动时间差',time_distance);
        var scroll_distance = cur_event.changedTouches[0].pageY - pre_event.touches[0].pageY;
//                scroll_distance = scroll_distance<0?-scroll_distance:scroll_distance;
//                console.log('滚动距离差',scroll_distance);

        //之前的tansform的Y轴值
        var pre_translate_val = _self.scroll_data.cur_translate_val;
//                console.log(_self.scroll_data);
        //当前tansform的Y轴值
        var cur_translate_val = _self.getTranformY($this);
        if (time_distance < 150) {
          cur_translate_val += scroll_distance * 5;
        }

        //上拉选择当前的上一个，下拉选择当前的下一个
        var item_height = _self.scroll_data.picker_item_height;
        /*if(pre_translate_val>cur_translate_val+item_height*0.5){
            console.log('上拉');
            cur_translate_val = cur_translate_val-cur_translate_val%item_height-item_height;
        }else if(pre_translate_val<=cur_translate_val-item_height*0.5){
            console.log('下拉');
            cur_translate_val = cur_translate_val-cur_translate_val%item_height;
        }*/
//                cur_translate_val = parseFloat(cur_translate_val.toFixed(4));
//                console.log('当前改变的位置',cur_translate_val);
        //处理滚动超出范围
        var max_distance = -($this.find('.picker_item').length - 5) * item_height;
//                console.log('最大距离',max_distance);
        if (cur_translate_val > 0) {
          cur_translate_val = 0;
        } else if (cur_translate_val < max_distance) {
          cur_translate_val = max_distance;
        }
        //设置当前选择
        var cur_list_index = $this[0].dataset.index;
        var cur_item_index = parseInt((-cur_translate_val / item_height).toFixed(0));
//                console.log('当前index',cur_list_index);
//                console.log('当前选择的index',cur_item_index);
//                console.log('当前选择的item',_self.cur_val);
        _self.scroll_data.scrolling_event = null;
        _self.scrollToItem(cur_list_index, cur_item_index);

      },
      //滚到指定项
      scrollToItem(i, j, stopEmit) {
        var _self = this;
        j = j || 0;
        /*var distance = -_self.scroll_data.picker_item_height*j;
        $($('#'+_self.id+' '+".picker_list")[i]).css({
            /!*'transition': 'transform 0.2s',
            'webkitTransition': 'transform 0.2s',
            'webkitTransform':'translateY('+distance+'px)',
            'transform':'translateY('+distance+'px)'*!/
            'transition': 'margin-top 0.2s',
            'webkitTransition': 'margin-top 0.2s',
            'margin-top':distance+'px'
        });*/

        //深度复制
        var val_arr = [];
        for (var key = 0; key < _self.cur_val.length; key++) {
          val_arr.push(_self.cur_val[key]);
        }
        val_arr[i] = _self.curData ? _self.curData[i][j] : _self.data[i][j];
        _self.cur_val = val_arr;
//                stopEmit?'':_self.$emit('scroll',_self.cur_val);//发射到滚动事件
      },
      /*//确定回调
      clickOk(){
          var _self = this;
          _self.close();
          _self.$emit('ok',_self.cur_val);
      },
      //取消回调
      clickCancel(e){
          var _self = this;
          _self.init();
          _self.close();
          _self.$emit('cancel');
      },*/
      close() {
//                this.cur_is_show = false;
        this.$emit('update:is_show', false);//触发.sync
        this.$emit('close');//触发.sync
      },
      getTranformY($obj) {
        var transform = $obj.css('-webkit-transform') || $obj.css('transform');
        var result = '0px';
        var transform_match = '';
        if (transform.indexOf('matrix') > -1) {
          transform_match = transform.replace(' ', '');
          transform_match = transform_match.replace(')', '');
          result = transform_match.split(',')[5] + 'px';
        } else if (transform.indexOf('translate') > -1) {
          transform_match = transform.match(/translate(Y|\dd)?\(\s*(\w+\s*,)?\s*([^,]+)(\s*,[^)]+)?\s*\)/);
          result = transform_match ? transform_match[3] : '0px';
        }
        result = parseFloat(result.replace('px', ''));
//        console.log(result);
        return result;
      },
      getMarginTop($obj) {
        return parseFloat($obj.css('margin-top').replace('px', ''));
      }
    },
    watch: {
      /*is_show(val) {
//                this.cur_is_show = val;
          this.$emit('update:is_show', val);
      }*/
      cur_val(val) {
//                console.log('自动同步数据',val);
        this.$emit('input', val);
      },
      value(val) {
        var _self = this;
        for (var i = 0; i < val.length; i++) {
//                    console.log(val[i],_self.cur_val[i]);
          /*if(val[i]==_self.cur_val[i]){
              continue;
          }*/

          var cur_index = 0;
          for (var j = 0; j < _self.data[i].length; j++) {
            if (val[i] == _self.data[i][j]) {
              cur_index = j;
              break;
            }
          }
          var distance = -_self.scroll_data.picker_item_height * cur_index;
          $($('#' + _self.id + ' ' + ".picker_list")[i]).css({
            /*'transition': 'transform 0.2s',
             'webkitTransition': 'transform 0.2s',
             'webkitTransform':'translateY('+distance+'px)',
             'transform':'translateY('+distance+'px)'*/

            /*'transition': 'margin-top 0.2s',
            'webkitTransition': 'margin-top 0.2s',
            'margin-top':distance+'px'*/

            'transition': 'transform 0.2s',
            '-webkit-transition': '-webkit-transform 0.2s',
            'transition-property': '-webkit-transform',
            'transform-origin': '0px 0px 0px',
            'transform': 'translate3d(0px, ' + distance + 'px, 0px) scale(1)',
            '-webkit-transform': 'translate3d(0px, ' + distance + 'px, 0px) scale(1)',
          });
        }
        _self.cur_val = val;
        _self.$emit('scroll', _self.cur_val)
      },
      data(val) {
        var _self = this;
        if (_self.curData == null) {
          _self.curData = val;
          return;
        }
        if (_self.curData.toString() != val.toString()) {
          for (var i = 0; i < val.length; i++) {
            if (_self.curData[i].toString() != val[i].toString()) {
              _self.curData[i] = val[i];
              var cur_index = 0;
              //如果更变的项目中有选中的，则自动选中
              //否则回到第一项
              for (var j = 0; j < val[i].length; j++) {
                if (_self.cur_val[i] == val[i][j]) {
                  cur_index = j;
                }
              }
              _self.scrollToItem(i, cur_index);
            }
          }
        }
      }
    },
  };
</script>
